package com.quanyan.club.pullclub.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.club.constants.ClubConstants;
import com.quanyan.club.constants.ClubRedisConstants;
import com.quanyan.club.entity.db.*;
import com.quanyan.club.mapper.*;
import com.quanyan.club.pullclub.entity.BatchSellRate;
import com.quanyan.club.pullclub.entity.req.*;
import com.quanyan.club.pullclub.entity.resp.RespChannelIncomes;
import com.quanyan.club.pullclub.entity.resp.RespHomePage;
import com.quanyan.club.pullclub.entity.resp.RespNewUserDetail;
import com.quanyan.club.pullclub.entity.resp.RespSellBusiness;
import com.quanyan.club.pullclub.service.PullClubOneService;
import com.quanyan.club.pullclub.service.PullClubSupportService;
import com.quanyan.club.pullclub.utils.DES;
import com.quanyan.club.pullclub.utils.NumUtils;
import com.quanyan.club.pullclub.utils.StringUtils;
import com.quanyan.club.pullclub.web.PullClubController;
import com.quanyan.club.service.impl.BaseServiceImpl;
import com.quanyan.club.sms.ClubSmsService;
import com.quanyan.club.util.qrcode.ImageUtils;
import com.quanyan.club.util.qrcode.ZXingCodeUtil;
import com.quanyan.club.util.qrcode.util.CodeColor;
import com.quanyan.club.util.qrcode.util.CodeConfig;
import com.quanyan.club.util.qrcode.util.LogoConfig;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.constants.Constants;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.Limit;
import com.quanyan.common.utils.ShortUrlUtils;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.redisCluster.config.RedisTemplate;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import com.quanyan.user.request.ReqInsideUserRegister;
import com.quanyan.user.response.RespUserInfoBase;
import com.quanyan.user.serviceFacade.UserServiceFacade;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.util.*;
import java.util.List;

/**
 * Created by xian-guo on 2017/2/13.
 */
@Service("pullClubOneService")
public class PullClubOneServiceImpl extends BaseServiceImpl implements PullClubOneService {

    private static Logger logger = Logger.getLogger(PullClubOneServiceImpl.class);

    @Autowired
    private UserServiceFacade userServiceFacade;
    @Autowired
    private TbChannelUserMapper tbChannelUserMapper;
    @Autowired
    private PullClubMapper pullClubMapper;
    @Autowired
    private TbChannelMapper tbChannelMapper;
    @Autowired
    private TbChannelSellMapper tbChannelSellMapper;
    @Autowired
    private PullClubSupportService pullClubSupportService;
    @Autowired
    private ClubSmsService clubSmsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Value("${channel.url}")
    private String channelUrl;
    @Value("${ex.channel.url}")
    private String exChannelUrl;//推广

    /**
     * 渠道商注册
     *
     * @param reqRegisterMsg
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse channelRegister(ReqRegisterMsg reqRegisterMsg) {
        TbChannelExample tbChannelExample = new TbChannelExample();
        tbChannelExample.createCriteria().andChMobileEqualTo(reqRegisterMsg.getMobile());
        List<TbChannel> tbChannelList = tbChannelMapper.selectByExample(tbChannelExample);
        if (!CollectionUtils.isEmpty(tbChannelList)){
            TbChannel tbChannel= tbChannelList.get(0);
            if (tbChannel.getIsDelete()==1){//账户被冻结渠道商经销商不能登录
                return APIResponse.returnFail("您的账户已被冻结");
            }
        }
        Map<String, Object> codeMap = new HashMap<>();
        if (CollectionUtils.isEmpty(tbChannelList)) {//该渠道商不存在，插入
            TbChannel tbChanne=new TbChannel();
            tbChanne.setChMobile(reqRegisterMsg.getMobile());
            tbChanne.setSellCode(this.getCode("QC","QD"));
            tbChanne.setExCode(this.getCode("QS","QD"));
            tbChanne.setChType((byte) 0);
            int ins=tbChannelMapper.insertSelective(tbChanne);
            if (ins<=0){
                return APIResponse.returnFail("创建渠道商失败");
            }
            codeMap.put("sellCode", DES.encrypt("type=2&code=" + tbChanne.getSellCode()));//渠道商分销码
            codeMap.put("exCode", DES.encrypt("type=4&code=" + tbChanne.getExCode()));//渠道商推广码
            codeMap.put("mobile", tbChanne.getChMobile());
            codeMap.put("isChannel", "QD");
            if(reqRegisterMsg.getIsToken()==1){//token过期了
                codeMap.put("token",setTokenToRedis(tbChanne.getSellCode()));
            }
            return APIResponse.returnSuccess(codeMap);
        }
        TbChannel tbChannel = tbChannelList.get(0);
        codeMap.put("sellCode", DES.encrypt("type=2&code=" + tbChannel.getSellCode()));//渠道商分销码
        codeMap.put("exCode", DES.encrypt("type=4&code=" + tbChannel.getExCode()));//渠道商推广码
        codeMap.put("mobile", tbChannel.getChMobile());
        codeMap.put("isChannel", "QD");
        if(reqRegisterMsg.getIsToken()==1){//token过期了
            codeMap.put("token",setTokenToRedis(tbChannel.getSellCode()));
        }
        return APIResponse.returnSuccess(codeMap);
    }

    /**
     * 经销商注册
     * code为渠道商code
     *
     * @param reqRegisterMsg
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse sellRegister(ReqRegisterMsg reqRegisterMsg) {
        //查询渠道商
        TbChannelExample tbChannelExample = new TbChannelExample();
        tbChannelExample.createCriteria().andSellCodeEqualTo(reqRegisterMsg.getSellCode());
        List<TbChannel> tbChannelList = tbChannelMapper.selectByExample(tbChannelExample);
        if (CollectionUtils.isEmpty(tbChannelList)) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        TbChannel tbChannel = tbChannelList.get(0);
        if (tbChannel.getIsDelete()==1){//账户被冻结渠道商经销商不能登录
            return APIResponse.returnFail("您的账户已被冻结");
        }
        TbChannelSellExample tbChannelSellExample = new TbChannelSellExample();
        tbChannelSellExample.createCriteria().andSellMobileEqualTo(reqRegisterMsg.getMobile()).andChIdEqualTo(tbChannel.getId());
        List<TbChannelSell> tbChannelSells = tbChannelSellMapper.selectByExample(tbChannelSellExample);
        Map<String, Object> codeMap = new HashMap<>();
        if (CollectionUtils.isEmpty(tbChannelSells)) {
            //生成经销商code
            String code = this.getCode("FC","FX");
            //插入
            TbChannelSell tbChannelSell = new TbChannelSell();
            tbChannelSell.setChId(tbChannel.getId());
            tbChannelSell.setSellMobile(reqRegisterMsg.getMobile());
            tbChannelSell.setCode(code);
            tbChannelSell.setSellRate(tbChannel.getRate());
            int inser = tbChannelSellMapper.insertSelective(tbChannelSell);
            if (inser <= 0) {
                throw new BizException("登录失败");
            }
            codeMap.put("exCode", DES.encrypt("type=3&code=" + code));
            codeMap.put("mobile", reqRegisterMsg.getMobile());
            codeMap.put("isChannel", "FX");
            if(reqRegisterMsg.getIsToken()==1){//token过期了
                codeMap.put("token",setTokenToRedis(code));
            }
            return APIResponse.returnSuccess(codeMap);
        }
        codeMap.put("exCode", DES.encrypt("type=3&code=" + tbChannelSells.get(0).getCode()));
        codeMap.put("mobile", tbChannelSells.get(0).getSellMobile());
        codeMap.put("isChannel", "FX");
        if(reqRegisterMsg.getIsToken()==1){//token过期了
            codeMap.put("token",setTokenToRedis(tbChannelSells.get(0).getCode()));
        }
        return APIResponse.returnSuccess(codeMap);

    }

    /**
     * 用户退出
     * @param channelLoginOut
     * @return
     */
    @Override
    public APIResponse userLoginOut(ChannelLoginOut channelLoginOut) {
        if ("QD".equals(channelLoginOut.getIsChannel())) {//验证权限
            TbChannelExample tbChannelExample = new TbChannelExample();
            tbChannelExample.createCriteria().andChMobileEqualTo(channelLoginOut.getMobile()).andSellCodeEqualTo(channelLoginOut.getCode());
            List<TbChannel> tbChannelList = tbChannelMapper.selectByExample(tbChannelExample);
            if (CollectionUtils.isEmpty(tbChannelList)) {
                return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
            }
        }
        if ("FX".equals(channelLoginOut.getIsChannel())) {//验证权限
            TbChannelSellExample tbChannelSellExample = new TbChannelSellExample();
            tbChannelSellExample.createCriteria().andSellMobileEqualTo(channelLoginOut.getMobile()).andCodeEqualTo(channelLoginOut.getCode());
            List<TbChannelSell> tbChannelSellList = tbChannelSellMapper.selectByExample(tbChannelSellExample);
            if (CollectionUtils.isEmpty(tbChannelSellList)) {
                return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
            }
        }
        if (StringUtil.isNotBlank(channelLoginOut.getToken())){
            String key = ClubRedisConstants.CLUB_CHANNEL_TOKEN+channelLoginOut.getToken();
            RedisKey redisKey = new RedisKey(RedisConstants.CLUB_FAMILY_KEY, key);
            if (redisTemplate.exists(redisKey)){
                redisTemplate.delteKey(redisKey);
                return APIResponse.returnSuccess();
            }
        }
        return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
    }

    /**
     * 获取二维码
     * @param qrCodeReq
     * @return
     */
    @Override
    public APIResponse getZxingCode(QrCodeReq qrCodeReq) {
        if ("QD".equals(qrCodeReq.getChannel())){
            if (StringUtils.isNotBlankOrNull(qrCodeReq.getSellCode())){
                TbChannel tbChannel=this.isPermissionQD(qrCodeReq.getChannel(),qrCodeReq.getMobile(),qrCodeReq.getSellCode());
                if (null == tbChannel){
                    return APIResponse.returnFail(ApiResponseEnum.PERMISSION_DENIED);
                }
                //生成二维码字符串
                return APIResponse.returnSuccess(getZXingCodeStr(qrCodeReq.getUrl(),"sellCode",qrCodeReq.getDESsellCode()));
            }
            if (StringUtils.isNotBlankOrNull(qrCodeReq.getExCode())){
                if (!isPermissionAccess(qrCodeReq.getChannel(),qrCodeReq.getMobile(),qrCodeReq.getExCode())){
                    return APIResponse.returnFail(ApiResponseEnum.PERMISSION_DENIED);
                }
                //生成二维码字符串
                return APIResponse.returnSuccess(getZXingCodeStr(qrCodeReq.getUrl(),"exCode",qrCodeReq.getDESexCode()));
            }
        }else if ("FX".equals(qrCodeReq.getChannel())){
            if (StringUtils.isNotBlankOrNull(qrCodeReq.getExCode())){
                if (!isPermissionAccess(qrCodeReq.getChannel(),qrCodeReq.getMobile(),qrCodeReq.getExCode())){
                    return APIResponse.returnFail(ApiResponseEnum.PERMISSION_DENIED);
                }
                //生成二维码字符串
                return APIResponse.returnSuccess(getZXingCodeStr(qrCodeReq.getUrl(),"exCode",qrCodeReq.getDESexCode()));
            }
        }
        return null;
    }

    @Override
    public APIResponse PLQrCode(int uid, String url, String param, String data) {
        RespUserInfoBase userInfo = getUserInfoBase(uid);
        if (userInfo == null){
            return APIResponse.returnFail("用户未登陆");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("avatar", userInfo.getIcon());
        map.put("name", userInfo.getNickName());
        String paramVal = param + "=" + data + "&nickName=" + userInfo.getNickName();
        map.put("qrCode", getZXingCodeByUrl(url, paramVal));
        return APIResponse.returnSuccess(map);
    }

    /**
     * 普通用户注册
     *
     * @param reqRegisterMsg
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse customerRegister(ReqRegisterMsg reqRegisterMsg) {
        //该用户是否存在
        TbChannelUserExample tbChannelUserExample = new TbChannelUserExample();
        tbChannelUserExample.createCriteria().andMobileEqualTo(reqRegisterMsg.getMobile());
        int countByMobile = tbChannelUserMapper.countByExample(tbChannelUserExample);
        if (countByMobile > 0) {
            return APIResponse.returnSuccess("您已经是拉新用户！");
        }
        //插入拉新用户
        TbChannelUser tbChannelUser = new TbChannelUser();
        tbChannelUser.setMobile(reqRegisterMsg.getMobile());
        tbChannelUser.setCode(reqRegisterMsg.getSellCode());
        tbChannelUser.setType(reqRegisterMsg.getType());
        //老带新用户，查看链接是否有效
        if (reqRegisterMsg.getType() == 2) {
            APIResponse<RespUserInfoBase> apiResponse = userServiceFacade.queryUserInfo(Integer.valueOf(reqRegisterMsg.getSellCode()));
            if (!apiResponse.isRet() || apiResponse.getErrcode() != 200) {
                throw new BizException("注册失败，请重试");
            }
            RespUserInfoBase respUserInfoBase = apiResponse.getData();
            tbChannelUser.setOldClubMobile(respUserInfoBase.getMobile());
            tbChannelUser.setOldClubUid(respUserInfoBase.getUid());
        }
        int insertChannel = tbChannelUserMapper.insertSelective(tbChannelUser);
        if (insertChannel <= 0) {
            throw new BizException("注册失败");
        }
        //调用用户中心登录注册
        ReqInsideUserRegister reqInsideUserRegister = new ReqInsideUserRegister();
        reqInsideUserRegister.setSourceSystemId(Constants.CLUB_SYSTEM_CODE);
        reqInsideUserRegister.setSourceBusinessId(ClubConstants.CLUB_YEAR_ACTIVITY_CODE);
        reqInsideUserRegister.setPhone(reqRegisterMsg.getMobile());
        APIResponse<RespUserInfoBase> userInfoBaseAPIResponse = userServiceFacade.userInsideRegister(reqInsideUserRegister);
        if (!userInfoBaseAPIResponse.isRet() || userInfoBaseAPIResponse.getErrcode() != 200) {
            throw new BizException("注册失败,请重试");
        }
        if (userInfoBaseAPIResponse.getData().getIsNew() != 0) {//不是新用户
            throw new BizException("您已是平台用户，没有成为新用户的资格！");
        }
        //跟新uid
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("uId", userInfoBaseAPIResponse.getData().getUid());
        paramMap.put("mobile", userInfoBaseAPIResponse.getData().getMobile());
        int updateUid = pullClubMapper.updateChannelUser(paramMap);
        if (updateUid <= 0) {
            throw new BizException("注册失败");
        }
        return APIResponse.returnSuccess("恭喜您成为拉新新用户！");
    }

    /**
     * 进入首页数据
     *
     * @param reqHomePage
     * @return
     */
    @Override
    public APIResponse<RespHomePage> homePageData(ReqHomePage reqHomePage) {
        if (!"QD".equals(reqHomePage.getIsChannel()) && !"FX".equals(reqHomePage.getIsChannel())) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        RespHomePage respHomePage = new RespHomePage();
        Byte isChannel = 0;//渠道商or经销商
        List<RespChannelIncomes> idList1 = null;//累积收益
        if ("QD".equals(reqHomePage.getIsChannel())) {//渠道商
            //验证是否有权限进入该页面
            TbChannel tbChannel = this.isPermissionQD("QD", reqHomePage.getMobile(), reqHomePage.getSellCode());
            if (tbChannel == null) {
                return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
            }
            respHomePage.setSellCode(DES.encrypt("type=2&code=" + tbChannel.getSellCode()));
            respHomePage.setExCode(DES.encrypt("type=4&code=" + tbChannel.getExCode()));
            isChannel = 0;
            //累积收益
            idList1 = pullClubMapper.selectSellByIncome(Arrays.asList(tbChannel.getId()), isChannel);

            //设置分销码短连接
            String httpResult1 = ShortUrlUtils.getShortUrl(channelUrl+"?sellCode="+respHomePage.getSellCode());
            if (StringUtils.isNotBlankOrNull(httpResult1)) {
                JSONArray jsonArray=JSONArray.parseArray(httpResult1);
                JSONObject jsonObject= (JSONObject) jsonArray.get(0);
                respHomePage.setSellCodeUrl(jsonObject.getString("url_short"));
            }else {
                respHomePage.setSellCodeUrl(channelUrl+"?sellCode="+respHomePage.getSellCode());
            }
        }
        if ("FX".equals(reqHomePage.getIsChannel())) {//经销商
            //验证是否有权限进入该页面
            TbChannelSell tbChannelSell = this.isPermissionFX("FX", reqHomePage.getMobile(), reqHomePage.getExCode());
            if (tbChannelSell == null) {
                return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
            }
            respHomePage.setExCode(DES.encrypt("type=3&code=" + tbChannelSell.getCode()));
            isChannel = 1;
            //累积收益
            idList1 = pullClubMapper.selectSellByIncome(Arrays.asList(tbChannelSell.getId()), isChannel);

        }
        //设置推广码短连接
        String httpResult1 = ShortUrlUtils.getShortUrl(exChannelUrl+"?exCode="+respHomePage.getExCode());
        if (StringUtils.isNotBlankOrNull(httpResult1)) {
            JSONArray jsonArray=JSONArray.parseArray(httpResult1);
            JSONObject jsonObject= (JSONObject) jsonArray.get(0);
            respHomePage.setExCodeUrl(jsonObject.getString("url_short"));
        }else {
            respHomePage.setExCodeUrl(exChannelUrl+"?exCode="+respHomePage.getExCode());
        }

        if (!CollectionUtils.isEmpty(idList1)) {
            respHomePage.setSumMoney(idList1.get(0).getSumIncome());
        }
        respHomePage.setIsChannel(reqHomePage.getIsChannel());
        //成功拉新人数
        respHomePage.setNewUserNum(getNewUserNumSucc(isChannel, reqHomePage.getExCode()));
        return APIResponse.returnSuccess(respHomePage);
    }

    /**
     * 渠道商页面中的经销商页面
     *
     * @param reqSellBusiness
     * @return
     */
    @Override
    public APIResponse<Map<String,Object>> sellBusinessPageData(ReqSellBusiness reqSellBusiness) {
        //验证是否有权限进入该页面
        TbChannel tbChannel = this.isPermissionQD("QD", reqSellBusiness.getChannelMobile(), reqSellBusiness.getChannelCode());
        if (tbChannel == null) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        Map<String,Object> param=new HashMap<>();
        param.put("rate",tbChannel.getRate());
        List<RespSellBusiness> respSellBusinessList = new ArrayList<>();//中间集合
        List<RespSellBusiness> respSellBusinessList2 = new ArrayList<>();//返回集合
        switch (reqSellBusiness.getType()) {
            case 0://进入页面
                TbChannelSellExample tbChannelSellExample = new TbChannelSellExample();
                tbChannelSellExample.createCriteria().andChIdEqualTo(tbChannel.getId()).andSellMobileNotIn(Arrays.asList(tbChannel.getChMobile()));
                int totalCount=tbChannelSellMapper.countByExample(tbChannelSellExample);
                tbChannelSellExample.setLimit(Limit.buildLimit(reqSellBusiness.getPageNum()+1,reqSellBusiness.getPageSize()));
                List<TbChannelSell> tbChannelSellList = tbChannelSellMapper.selectByExample(tbChannelSellExample);
                List<String> sellCodeList = new ArrayList<>();//保存经销商code，查询成功拉新人数
                List<Integer> sellIdList = new ArrayList<>();//保存经销商id，查询每个经销商收益
                for (TbChannelSell tbChannelSell : tbChannelSellList) {
                    RespSellBusiness respSellBusiness = new RespSellBusiness();
                    respSellBusiness.setMobile(tbChannelSell.getSellMobile());
                    respSellBusiness.setCreateTime(tbChannelSell.getCreateTime());
                    respSellBusiness.setRate(tbChannelSell.getSellRate());
                    respSellBusiness.setCode(tbChannelSell.getCode());
                    respSellBusiness.setSellId(tbChannelSell.getId());
                    respSellBusinessList.add(respSellBusiness);
                    sellCodeList.add(tbChannelSell.getCode());
                    sellIdList.add(tbChannelSell.getId());
                    respSellBusinessList2.add(respSellBusiness);
                }
                //查询累积收益,并根据累积收益倒序
                if (!CollectionUtils.isEmpty(sellIdList)) {
                    List<RespChannelIncomes> idList = pullClubMapper.selectSellByIncome(sellIdList, 1);
                    if (!CollectionUtils.isEmpty(idList)) {
                        respSellBusinessList2.clear();
                        for (RespChannelIncomes respChannelIncomes : idList) {
                            for (RespSellBusiness respSellBusiness : respSellBusinessList) {
                                if (respChannelIncomes.getRoleId().equals(respSellBusiness.getSellId())) {//经销商累积收益
                                    respSellBusiness.setSumMoney(respChannelIncomes.getSumIncome());
                                    respSellBusinessList2.add(respSellBusiness);
                                    break;
                                }
                            }
                        }
                    }
                }
                respSellBusinessList.removeAll(respSellBusinessList2);//移除成功拉新的经销商，因为没有收益是没有记录的
                respSellBusinessList2.addAll(respSellBusinessList);//把未成功拉新的加入进来
                //查询成功拉新的人数
                if (!CollectionUtils.isEmpty(sellCodeList)) {
                    List<RespChannelIncomes> mapList = pullClubMapper.getNewUserNum(sellCodeList);
                    if (!CollectionUtils.isEmpty(mapList)) {
                        for (RespSellBusiness respSellBusiness : respSellBusinessList2) {
                            //设置渠道商和经销商各自获得的钱
                            BigDecimal sellMoney = respSellBusiness.getSumMoney().multiply(new BigDecimal(Float.toString(respSellBusiness.getRate())));
                            respSellBusiness.setSellMoney(sellMoney);
                            respSellBusiness.setChannelMoney(respSellBusiness.getSumMoney().subtract(sellMoney));
                            for (RespChannelIncomes respSellBu : mapList) {
                                if (respSellBu.getCode().equals(respSellBusiness.getCode())) {//拉用人数
                                    respSellBusiness.setNewUserNum(respSellBu.getNewUserNun());
                                    break;
                                }
                            }
                        }
                    }
                }
                for (RespSellBusiness respSellBusiness : respSellBusinessList2) {
                    respSellBusiness.setCode(DES.encrypt("type=2&code=" + respSellBusiness.getCode()));
                }
                PageObj<List<RespSellBusiness>> result=PageObj.create(totalCount,reqSellBusiness.getPageNum(),reqSellBusiness.getPageSize(),respSellBusinessList2);
                param.put("result",result);
                return APIResponse.returnSuccess(param);
            case 1://排序
                TbChannelSellExample tbChannelSellExample1 = new TbChannelSellExample();
                tbChannelSellExample1.createCriteria().andChIdEqualTo(tbChannel.getId()).andSellMobileNotIn(Arrays.asList(tbChannel.getChMobile()));
                int totalCount1=tbChannelSellMapper.countByExample(tbChannelSellExample1);
                tbChannelSellExample1.setLimit(Limit.buildLimit(reqSellBusiness.getPageNum()+1,reqSellBusiness.getPageSize()));
                List<TbChannelSell> tbChannelSellList1 = tbChannelSellMapper.selectByExample(tbChannelSellExample1);
                List<String> sellCodeList1 = new ArrayList<>();//保存经销商code，查询成功拉新人数
                List<Integer> sellIdList1 = new ArrayList<>();//保存经销商id，查询每个经销商收益
                for (TbChannelSell tbChannelSell : tbChannelSellList1) {
                    RespSellBusiness respSellBusiness1 = new RespSellBusiness();
                    respSellBusiness1.setMobile(tbChannelSell.getSellMobile());
                    respSellBusiness1.setCreateTime(tbChannelSell.getCreateTime());
                    respSellBusiness1.setRate(tbChannelSell.getSellRate());
                    respSellBusiness1.setSellId(tbChannelSell.getId());
                    respSellBusiness1.setCode(tbChannelSell.getCode());
                    respSellBusinessList.add(respSellBusiness1);
                    sellCodeList1.add(tbChannelSell.getCode());
                    sellIdList1.add(tbChannelSell.getId());
                    respSellBusinessList2.add(respSellBusiness1);
                }
                //查询成功拉新的人数
                if (!CollectionUtils.isEmpty(sellCodeList1)) {
                    List<RespChannelIncomes> mapList1 = pullClubMapper.getNewUserNum(sellCodeList1);
                    if (!CollectionUtils.isEmpty(mapList1)) {
                        respSellBusinessList2.clear();
                        for (RespChannelIncomes respSellBu : mapList1) {
                            for (RespSellBusiness respSellBusiness1 : respSellBusinessList) {
                                if (respSellBusiness1.getCode().equals(respSellBu.getCode())) {
                                    respSellBusiness1.setNewUserNum(respSellBu.getNewUserNun());
                                    respSellBusinessList2.add(respSellBusiness1);
                                    break;
                                }
                            }
                        }
                    }
                }
                respSellBusinessList.removeAll(respSellBusinessList2);//移除成功拉新的经销商，因为没有拉新成功是没有记录的
                respSellBusinessList2.addAll(respSellBusinessList);//把未成功拉新的加入进来
                //查询累积收入
                if (!CollectionUtils.isEmpty(sellIdList1)) {
                    List<RespChannelIncomes> idList1 = pullClubMapper.selectSellByIncome(sellIdList1, 1);
                    if (!CollectionUtils.isEmpty(idList1)) {
                        for (RespSellBusiness respSellBusiness : respSellBusinessList2) {
                            for (RespChannelIncomes respChannelIn : idList1) {
                                if (respSellBusiness.getSellId().equals(respChannelIn.getRoleId())) {
                                    respSellBusiness.setSumMoney(respChannelIn.getSumIncome());
                                    //设置渠道商和经销商各自获得的钱
                                    BigDecimal sellMoney = respChannelIn.getSumIncome().multiply(new BigDecimal(Float.toString(respSellBusiness.getRate())));
                                    respSellBusiness.setSellMoney(sellMoney);
                                    respSellBusiness.setChannelMoney(respChannelIn.getSumIncome().subtract(sellMoney));
                                    break;
                                }
                            }
                        }
                    }
                }
                for (RespSellBusiness respSellBusiness : respSellBusinessList2) {
                    respSellBusiness.setCode(DES.encrypt("type=2&code=" + respSellBusiness.getCode()));
                }
                PageObj<List<RespSellBusiness>> result1=PageObj.create(totalCount1,reqSellBusiness.getPageNum(),reqSellBusiness.getPageSize(),respSellBusinessList2);
                param.put("result",result1);
                return APIResponse.returnSuccess(param);
            case 2://搜索
                if (StringUtil.isBlankOrNull(reqSellBusiness.getMobile())) {
                    return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
                }
                TbChannelSellExample tbChannelSellExample2 = new TbChannelSellExample();
                tbChannelSellExample2.createCriteria().andChIdEqualTo(tbChannel.getId()).andSellMobileEqualTo(reqSellBusiness.getMobile()).andSellMobileNotIn(Arrays.asList(tbChannel.getChMobile()));;
                List<TbChannelSell> tbChannelSellList2 = tbChannelSellMapper.selectByExample(tbChannelSellExample2);
                if (CollectionUtils.isEmpty(tbChannelSellList2)) {
                    return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
                }
                TbChannelSell tbChannelSel2 = tbChannelSellList2.get(0);
                List<RespSellBusiness> respSellBusinessList3 = new ArrayList<>();
                RespSellBusiness respSellBusiness2 = new RespSellBusiness();
                respSellBusiness2.setCreateTime(tbChannelSel2.getCreateTime());
                respSellBusiness2.setMobile(tbChannelSel2.getSellMobile());
                respSellBusiness2.setRate(tbChannelSel2.getSellRate());
                respSellBusiness2.setCode(DES.encrypt("type=2&code=" + tbChannelSel2.getCode()));
                //查询拉新人数
                List<RespChannelIncomes> mapList2 = pullClubMapper.getNewUserNum(Arrays.asList(tbChannelSel2.getCode()));
                if (!CollectionUtils.isEmpty(mapList2)) {
                    respSellBusiness2.setNewUserNum(mapList2.get(0).getNewUserNun());
                }
                //查询累积收入
                List<RespChannelIncomes> idList2 = pullClubMapper.selectSellByIncome(Arrays.asList(tbChannelSel2.getId()), 1);
                if (!CollectionUtils.isEmpty(idList2)) {
                    respSellBusiness2.setSumMoney(idList2.get(0).getSumIncome());
                }
                BigDecimal sellMoney = respSellBusiness2.getSumMoney().multiply(new BigDecimal(Float.toString(respSellBusiness2.getRate())));
                respSellBusiness2.setSellMoney(sellMoney);
                respSellBusiness2.setChannelMoney(respSellBusiness2.getSumMoney().subtract(sellMoney));
                respSellBusinessList3.add(respSellBusiness2);
                PageObj<List<RespSellBusiness>> result2=PageObj.create(1,1,1,respSellBusinessList3);
                param.put("result",result2);
                return APIResponse.returnSuccess(param);
            default:
                return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
    }

    /**
     * 设置经销商渠道商比例
     *
     * @param reqSellBusinessRate
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public APIResponse setSellBusinessRate(ReqSellBusinessRate reqSellBusinessRate) {
        //校验参数
        List<Map<String, Object>> mapList = reqSellBusinessRate.getParamMap();
        if (CollectionUtils.isEmpty(mapList)) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        //验证是否有权限进入该页面
        TbChannel tbChannel = this.isPermissionQD("QD", reqSellBusinessRate.getChannelMobile(), reqSellBusinessRate.getChannelCode());
        if (tbChannel == null) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        if (reqSellBusinessRate.getType() == 0) {//设置默认
            Map<String, Object> rat = mapList.get(0);
            if (!rat.containsKey("rate")) {
                return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
            }
            int rate = (int) rat.get("rate");
            double r= rate * 0.01d;
            if (!NumUtils.isCurrectNum((float) r)) {//验证是否有效
                return APIResponse.returnFail("参数异常");
            }
            Map<String, Object> rateMap = new HashMap<>();
            rateMap.put("rate", r);
            rateMap.put("chId", tbChannel.getId());
            int rateCou = pullClubMapper.updateSellChannelRate(rateMap);//设置渠道商默认分成比例
            if (rateCou <= 0) {
                throw new BizException("更改失败");
            }
            return APIResponse.returnSuccess("更新成功");
        }
        if (reqSellBusinessRate.getType() == 1) {//批量设置
            List<BatchSellRate> batchSellRates = new ArrayList<>();
            for (Map<String, Object> paramMap : mapList) {
                if (!paramMap.containsKey("code") || !paramMap.containsKey("rate")) {
                    return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
                }
                Map<String, String> exParam = pullClubSupportService.getDecryptCode((String) paramMap.get("code"));
                if (!exParam.containsKey("type") || !exParam.containsKey("code")) {
                    return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
                }
                BatchSellRate batchSellRate = new BatchSellRate();
                batchSellRate.setCode(exParam.get("code"));
                int rate = (int) paramMap.get("rate");
                double r= rate * 0.01d;
                if (!NumUtils.isCurrectNum((float) r)){
                    throw new BizException("参数异常");
                }
                batchSellRate.setRate((float) r);
                batchSellRate.setChId(tbChannel.getId());
                batchSellRates.add(batchSellRate);
            }
            //跟新经销商比例
            int rateUp = pullClubMapper.batchUpdateSellChannelRate(batchSellRates);
            if (rateUp <= 0) {
                throw new BizException("更改失败");
            }
            return APIResponse.returnSuccess("更新成功");
        }
        return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
    }

    /**
     * 拉新人数详情页面
     *
     * @param reqNewUserDetail
     * @return
     */
    @Override
    public APIResponse<Map<String, Object>> getNewUserMessageDetail(ReqNewUserDetail reqNewUserDetail) {
        if (!"QD".equals(reqNewUserDetail.getIsChannel()) && !"FX".equals(reqNewUserDetail.getIsChannel())) {
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        if (!isPermissionAccess(reqNewUserDetail.getIsChannel(), reqNewUserDetail.getChannelMobile(), reqNewUserDetail.getCode())) {//检查是否有权限登录
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        byte isChan = 0;//默认渠道商
        if ("FX".equals(reqNewUserDetail.getIsChannel())) {//验证权限
            isChan = 1;
        }
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("newUserNumSucc", getNewUserNumSucc(isChan, reqNewUserDetail.getCode()));
        resultMap.put("newUserNum", getNewUserNum(isChan, reqNewUserDetail.getCode()));
        TbChannelUserExample tbChannelUserExample = new TbChannelUserExample();
        TbChannelUserExample.Criteria criteria=tbChannelUserExample.createCriteria();
        criteria.andTypeEqualTo(isChan).andCodeEqualTo(reqNewUserDetail.getCode());
        if (reqNewUserDetail.getType()==1){//成功拉新
            criteria.andStatusEqualTo((byte) 3);//code为推广码
        }else if (reqNewUserDetail.getType()==2){//未成功拉新的
            criteria.andStatusNotIn(Arrays.asList((byte)3));
        }
        int totalCount = tbChannelUserMapper.countByExample(tbChannelUserExample);
        tbChannelUserExample.setOrderByClause(" id DESC");
        tbChannelUserExample.setLimit(Limit.buildLimit(reqNewUserDetail.getPageNum() + 1, reqNewUserDetail.getPageSize()));
        List<TbChannelUser> tbChannelUserList = tbChannelUserMapper.selectByExample(tbChannelUserExample);
        List<RespNewUserDetail> respNewUserDetailList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(tbChannelUserList)) {
            for (TbChannelUser tbChannelUser : tbChannelUserList) {
                RespNewUserDetail respNewUserDetail = new RespNewUserDetail();
                respNewUserDetail.setCreateTime(tbChannelUser.getCreateTime());
                respNewUserDetail.setMobile(tbChannelUser.getMobile());
                respNewUserDetail.setStatus(tbChannelUser.getStatus());
                respNewUserDetailList.add(respNewUserDetail);
            }
        }
        resultMap.put("resultList", PageObj.create(totalCount, reqNewUserDetail.getPageNum(), reqNewUserDetail.getPageSize(), respNewUserDetailList));
        return APIResponse.returnSuccess(resultMap);
    }


    /**
     * 获取成功拉新人数
     *
     * @param isChannel
     * @param code
     * @return
     */
    private int getNewUserNumSucc(Byte isChannel, String code) {
        TbChannelUserExample tbChannelUserExample = new TbChannelUserExample();
        tbChannelUserExample.createCriteria().andStatusEqualTo((byte) 3).andTypeEqualTo(isChannel).andCodeEqualTo(code);
        return tbChannelUserMapper.countByExample(tbChannelUserExample);
    }

    /**
     * 获取拉新人数
     *
     * @param isChannel
     * @param code
     * @return
     */
    private int getNewUserNum(Byte isChannel, String code) {
        TbChannelUserExample tbChannelUserExample = new TbChannelUserExample();
        tbChannelUserExample.createCriteria().andTypeEqualTo(isChannel).andCodeEqualTo(code);
        return tbChannelUserMapper.countByExample(tbChannelUserExample);
    }

    /**
     * 获取code
     *
     * @param str
     * @return
     */
    private String getCode(String str,String channel) {
        String num = str + RandomStringUtils.randomAlphanumeric(11);//生随机码
        if ("FX".equals(channel)){
            TbChannelSellExample tbChannelSellExample = new TbChannelSellExample();
            tbChannelSellExample.createCriteria().andCodeEqualTo(num);
            int countNum = tbChannelSellMapper.countByExample(tbChannelSellExample);
            if (countNum > 0) {
                getCode(str,channel);
            }
        }
        if ("QD".equals(channel)){
            if ("QC".equals(str)){
                TbChannelExample tbChannelExample=new TbChannelExample();
                tbChannelExample.createCriteria().andSellCodeEqualTo(num);
                int countNum=tbChannelMapper.countByExample(tbChannelExample);
                if (countNum > 0) {
                    getCode(str,channel);
                }
            }
            if ("QS".equals(str)){
                TbChannelExample tbChannelExample=new TbChannelExample();
                tbChannelExample.createCriteria().andExCodeEqualTo(num);
                int countNum=tbChannelMapper.countByExample(tbChannelExample);
                if (countNum > 0) {
                    getCode(str,channel);
                }
            }
        }
        return num;
    }

    /**
     * 是否有权限
     *
     * @param isChannel
     * @param mobile
     * @param code
     * @return
     */
    private boolean isPermissionAccess(String isChannel, String mobile, String code) {
        if ("QD".equals(isChannel)) {//验证权限
            TbChannelExample tbChannelExample = new TbChannelExample();
            tbChannelExample.createCriteria().andChMobileEqualTo(mobile).andExCodeEqualTo(code);
            List<TbChannel> tbChannelList = tbChannelMapper.selectByExample(tbChannelExample);
            if (CollectionUtils.isEmpty(tbChannelList)) {
                return false;
            }
        }
        if ("FX".equals(isChannel)) {//验证权限
            TbChannelSellExample tbChannelSellExample = new TbChannelSellExample();
            tbChannelSellExample.createCriteria().andSellMobileEqualTo(mobile).andCodeEqualTo(code);
            List<TbChannelSell> tbChannelSellList = tbChannelSellMapper.selectByExample(tbChannelSellExample);
            if (CollectionUtils.isEmpty(tbChannelSellList)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 渠道商验证权限
     *
     * @param isChannel
     * @param mobile
     * @param code
     * @return
     */
    private TbChannel isPermissionQD(String isChannel, String mobile, String code) {
        if ("QD".equals(isChannel)) {//验证权限
            TbChannelExample tbChannelExample = new TbChannelExample();
            tbChannelExample.createCriteria().andChMobileEqualTo(mobile).andSellCodeEqualTo(code);
            List<TbChannel> tbChannelList = tbChannelMapper.selectByExample(tbChannelExample);
            if (CollectionUtils.isEmpty(tbChannelList)) {
                return null;
            }
            return tbChannelList.get(0);
        }
        return null;
    }

    /**
     * 经销商验证权限
     *
     * @param isChannel
     * @param mobile
     * @param code
     * @return
     */
    private TbChannelSell isPermissionFX(String isChannel, String mobile, String code) {
        if ("FX".equals(isChannel)) {//验证权限
            TbChannelSellExample tbChannelSellExample = new TbChannelSellExample();
            tbChannelSellExample.createCriteria().andSellMobileEqualTo(mobile).andCodeEqualTo(code);
            List<TbChannelSell> tbChannelSellList = tbChannelSellMapper.selectByExample(tbChannelSellExample);
            if (CollectionUtils.isEmpty(tbChannelSellList)) {
                return null;
            }
            return tbChannelSellList.get(0);
        }
        return null;
    }

    /**
     * 生成token翻入缓存
     * @param code
     * @return
     */
    private String setTokenToRedis(String code){
        String tail= RandomStringUtils.randomAlphanumeric(10);
        String key = ClubRedisConstants.CLUB_CHANNEL_TOKEN+code+tail;
        RedisKey redisKey = new RedisKey(RedisConstants.CLUB_FAMILY_KEY, key);
        if (redisTemplate.exists(redisKey)){
            setTokenToRedis(code);
        }
        redisTemplate.setWithExpireTime(redisKey,code,3 * 24 * 60 * 60);//缓存一天
        return tail;
    }

    /**
     * 生成二维码
     * @param url
     * @param param
     * @param code
     * @return
     */
    public String getZXingCodeStr(String url,String param,String code) {
        String content = url+"?"+param+"="+code;
        return getQrCodeString(content);
    }

    public String getZXingCodeByUrl(String url,String param) {
        String content = url+"?"+param;
        return getQrCodeString(content);
    }

    private String getQrCodeString(String content){
        try {
            ZXingCodeUtil zp = new ZXingCodeUtil();
            CodeConfig zxingconfig = new CodeConfig();
            zxingconfig.setHints(zp.getDecodeHintType());
            zxingconfig.setContent(content);
            zxingconfig.setLogoPath(ImageUtils.larkLogo);
            zxingconfig.setLogoConfig(new LogoConfig());
            zxingconfig.setLogoFlag(true); // 设置生成Logo图片
            zxingconfig.setCodeColor(new CodeColor(Color.BLACK, Color.WHITE));//设置二维码颜色
            BufferedImage bim = zp.getQR_CODEBufferedImage(zxingconfig);// 生成二维码
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ImageIO.write(bim, "png", out); // 图片写出
            String str= ImageUtils.setImageBase64(out.toByteArray()).replace("\r\n","");
            return str;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static void main(String[] args) {
//        PullClubOneServiceImpl pullClubOneService=new PullClubOneServiceImpl();
//        System.out.println(pullClubOneService.getZXingCodeStr("http://www.baidu.com","exCode","FC2VsjsBtBk3j"));
    }
}
